package com.sunny.ihealth;

import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.sunny.ihealth.entity.bmob.UserInfo;
import com.sunny.ihealth.utils.MyTextUtils;
import com.sunny.ihealth.utils.NetworkUtils;

public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    private TextInputLayout textInputLayoutName, textInputLayoutPwd;
    private EditText etUsername, etPassword;
    private Button btnRegister;

    private BmobManager bmob;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initViews();
        bmob = new BmobManager(this);
    }

    private void initViews() {
        setStatusBarColor();
        setToolbar("注册");

        textInputLayoutName = (TextInputLayout) findViewById(R.id.textInputLayout_register_username);
        textInputLayoutPwd = (TextInputLayout) findViewById(R.id.textInputLayout_register_password);
        etUsername = textInputLayoutName.getEditText();
        etPassword = textInputLayoutPwd.getEditText();
        btnRegister = (Button) findViewById(R.id.btn_register_register);

        btnRegister.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if (!NetworkUtils.isNetworkAvailable(RegisterActivity.this, true)) {
            return;
        }
        String username = etUsername.getText().toString();
        String password = etPassword.getText().toString();
        if (!MyTextUtils.isLength(username, 3, 16)) {
            Toast.makeText(RegisterActivity.this, "账号格式有误，长度应在3-16位~", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!MyTextUtils.isLength(password, 6, 16)) {
            Toast.makeText(RegisterActivity.this, "密码格式有误，长度应在6-16位~", Toast.LENGTH_SHORT).show();
            return;
        }

        btnRegister.setEnabled(false);
        register(username, password);
    }


    private void register(final String username, final String password) {
        bmob.registerUser(username, password, new BmobManager.Action1<Boolean>() {
            @Override
            public void onCompleted(Boolean success) {
                if (success) {
                    login(username, password);
                } else {
                    btnRegister.setEnabled(true);
                }
            }
        });
    }


    private void login(String username, String password) {
        bmob.login(username, password, new BmobManager.Action1<UserInfo>() {
            @Override
            public void onCompleted(UserInfo userInfo) {
                btnRegister.setEnabled(true);
                if (userInfo != null) {

                } else {

                }
            }
        });
    }
}
